﻿//<TunynetCopyright>
//--------------------------------------------------------------
//<copyright>青岛拓宇网络科技有限公司 2005-2008</copyright>
//<version>V0.5</verion>
//<createdate>2008-3-4</createdate>
//<author>mazq</author>
//<email>mazq@tunynet.com</email>
//<log date="2008-3-4">创建</log>
//--------------------------------------------------------------
//</TunynetCopyright>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using ChinaCustoms.Qingdao.Workflow.Supports;
using System.Web.UI.HtmlControls;
using ChinaCustoms.Qingdao.Workflow.Activities;
using System.Workflow.Runtime;
using ChinaCustoms.Qingdao.Workflow.Permissions;
using TunyNet.Web.UI;
using System.Collections.ObjectModel;
using System.Web;
using System.Configuration;
using System.Xml;
using ChinaCustoms.Framework.DeluxeWorks.Library.OGUPermission;
using System.IO;

namespace ChinaCustoms.Qingdao.Workflow.Controls
{
    /// <summary>
    /// 工作流控制
    /// </summary>
    [ToolboxData("<{0}:WorkflowController runat=server></{0}:WorkflowController>")]
    public class WorkflowController : TemplatedWebControl
    {
        /// <summary>
        /// 应用程序CodeName
        /// </summary>
        private static readonly string ApplicationCodeName = ConfigurationManager.AppSettings["ApplicationCodeName"];

        /// <summary>
        /// 登录URL
        /// </summary>
        private static readonly string LoginUrl = ConfigurationManager.AppSettings["LoginUrl"];

        /// <summary>
        /// 下一步 流向事件的 参数(内部包括 流向列表)
        /// </summary>
        WorkflowChangeNextStepEventArgs workflowNextStepChooseEventArgs = null;

        protected override void OnInit(EventArgs e)
        {
            if (SkinName == null)
                ExternalSkinFileName = "Skin-WorkflowController.ascx";
            else
                ExternalSkinFileName = SkinName;

            base.OnInit(e);
        }

        #region Child Controls

        HtmlContainerControl inputPostilBlock;
        TextBox postil;

        HtmlContainerControl nextActionSettingBlock;
        HtmlContainerControl nextActionBlock;

        HtmlContainerControl nextActionSelectArea;
        DropDownList nextActionSelect;

        HtmlContainerControl nextActivityExecutorArea;
        Label nextActivityExecutorLabel;
        HtmlInputHidden nextActivityExecutorHidden;
        ModalLink nextActivityExecutorLink;
        CustomValidator nextActivityExecutorCustomValidator;

        HtmlContainerControl subFlowOrganizationsArea;
        Label subFlowOrganizationsLabel;
        HtmlInputHidden subFlowOrganizationsHidden;
        ModalLink subFlowOrganizationsLink;
        CustomValidator subFlowOrganizationsCustomValidator;

        HtmlContainerControl buttonBlock;
        LinkButton saveButton;
        LinkButton nextStepButton;

        HyperLink workflowTrackingLink;
        #endregion

        protected override void AttachChildControls()
        {
            inputPostilBlock = FindControl("InputPostilBlock") as HtmlContainerControl;
            postil = FindControl("Postil") as TextBox;

            nextActionSettingBlock = FindControl("NextActionSettingBlock") as HtmlContainerControl;
            nextActionBlock = FindControl("NextActionBlock") as HtmlContainerControl;

            nextActionSelectArea = FindControl("NextActionSelectArea") as HtmlContainerControl;
            nextActionSelect = FindControl("NextActionSelect") as DropDownList;
            nextActionSelect.AutoPostBack = true;
            nextActionSelect.SelectedIndexChanged += new EventHandler(NextActionSelect_SelectedIndexChanged);

            nextActivityExecutorArea = FindControl("NextActivityExecutorArea") as HtmlContainerControl;
            nextActivityExecutorLabel = FindControl("NextActivityExecutorLabel") as Label;
            nextActivityExecutorHidden = FindControl("NextActivityExecutorHidden") as HtmlInputHidden;
            nextActivityExecutorLink = FindControl("NextActivityExecutorLink") as ModalLink;
            nextActivityExecutorCustomValidator = FindControl("NextActivityExecutorCustomValidator") as CustomValidator;

            subFlowOrganizationsArea = FindControl("SubFlowOrganizationsArea") as HtmlContainerControl;
            subFlowOrganizationsLabel = FindControl("SubFlowOrganizationsLabel") as Label;
            subFlowOrganizationsHidden = FindControl("SubFlowOrganizationsHidden") as HtmlInputHidden;
            subFlowOrganizationsLink = FindControl("SubFlowOrganizationsLink") as ModalLink;
            subFlowOrganizationsCustomValidator = FindControl("SubFlowOrganizationsCustomValidator") as CustomValidator;

            buttonBlock = FindControl("ButtonBlock") as HtmlContainerControl;

            saveButton = FindControl("SaveButton") as LinkButton;
            if (saveButton != null)
                saveButton.Click += new EventHandler(SaveButton_Click);

            nextStepButton = FindControl("NextStepButton") as LinkButton;
            if (nextStepButton != null)
                nextStepButton.Click += new EventHandler(NextStepButton_Click);

            workflowTrackingLink = FindControl("WorkflowTrackingLink") as HyperLink;
        }


        /// <summary>
        /// 页面载入
        /// </summary>
        /// <param name="e"></param>
        protected override void OnLoad(EventArgs e)
        {
            //如果用户没有登录，则转向登录页面
            if (!Context.Request.IsAuthenticated)
                Context.Response.Redirect(LoginUrl);

            base.OnLoad(e);
            EnsureChildControls();

            if (!Page.IsPostBack)
            {
                //是否创建新的工作流实例
                bool isStartWorkflow = false;
                if (!string.IsNullOrEmpty(this.Context.Request.QueryString["StartWorkflow"]))
                {
                    try
                    {
                        isStartWorkflow = bool.Parse(this.Context.Request.QueryString["StartWorkflow"]);
                    }
                    catch { }
                }

                //创建新的工作流实例
                if (isStartWorkflow)
                {
                    #region 创建WorkflowInstance
                    WorkflowInstanceInfo workflowInstance = new WorkflowInstanceInfo();
                    workflowInstance.WorkflowGuid = Guid.NewGuid();
                    workflowInstance.CreateDate = DateTime.Now;
                    WorkflowInstances.CreateWorkflow(workflowInstance);
                    #endregion

                    #region 获取工作流原型数据

                    if (string.IsNullOrEmpty(this.WorkflowXmlFile))
                    {
                        ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.GetType().FullName, "alert('必须设置WorkflowController的WorkflowXmlFile属性！')", true);
                        return;
                    }
                    else
                    {
                        WorkflowHelper.ParseAndSaveWorkflow(this.WorkflowXmlFile, workflowInstance.WorkflowGuid);
                    }

                    #endregion

                    #region 创建Task
                    TaskInfo taskInfo = new TaskInfo();
                    taskInfo.TaskGuid = Guid.NewGuid();
                    taskInfo.WorkflowGuid = workflowInstance.WorkflowGuid;
                    taskInfo.TaskName = this.TaskName;
                    taskInfo.TaskType = this.TaskType;
                    taskInfo.ApplicationCodeName = ApplicationCodeName;

                    taskInfo.ApplicationName = ChinaCustomsPermissionWrapper.GetApplication(ApplicationCodeName).Name;

                    taskInfo.SponsorUserName = PermissionUtils.StripIrrespectiveCharsForLogOnName(this.Context.User.Identity.Name);
                    IUser currentUser = ChinaCustomsPermissionWrapper.GetUser(taskInfo.SponsorUserName);
                    if (currentUser != null)
                    {
                        taskInfo.SponsorDisplayName = currentUser.DisplayName;
                        taskInfo.SponsorFullPath = currentUser.FullPath;
                    }

                    ActivityPrototypeInfo firstActivityPrototype = ActivityPrototypes.GetFirstActivityPrototypeOfMainFlow(workflowInstance.WorkflowGuid);

                    taskInfo.ExecutingActivityCodeName = firstActivityPrototype.CodeName;
                    Tasks.CreateTask(taskInfo);
                    #endregion

                    #region 创建First ActivityInstance
                    firstActivityPrototype.RequiredUserNames = taskInfo.SponsorUserName;
                    ActivityPrototypes.UpdateActivityPrototype(firstActivityPrototype);

                    //根据活动获取的活动原型，创建具体活动；在创建活动的同时 生成工作项。
                    ActivityInstanceInfo activityInstance = new ActivityInstanceInfo(firstActivityPrototype);
                    ActivityInstances.CreateActivity(activityInstance, true, currentUser.LogOnName, Guid.Empty, null);
                    #endregion

                    WorkItemInfo firstWorkItem = WorkItems.GetFirstWorkItem(taskInfo.TaskGuid);

                    this.WorkItemGuid = firstWorkItem.WorkItemGuid;
                    this.TaskGuid = firstWorkItem.TaskGuid;
                    this.ActivityCodeName = firstActivityPrototype.CodeName;
                }
                else
                {
                    if (!string.IsNullOrEmpty(this.Context.Request.QueryString["WorkItemGuid"]))
                        this.WorkItemGuid = new Guid(this.Context.Request.QueryString["WorkItemGuid"]);

                    if (!string.IsNullOrEmpty(this.Context.Request.QueryString["TaskGuid"]))
                        this.TaskGuid = new Guid(this.Context.Request.QueryString["TaskGuid"]);

                    this.ActivityCodeName = this.Context.Request.QueryString["ActivityCodeName"];
                }


                #region 以下是处理 下一步执行选项
                if (this.WorkItemGuid == Guid.Empty && this.TaskGuid == Guid.Empty)
                {
                    this.Visible = false;
                    return;
                }
                else
                {
                    if (CurrentWorkItem == null)
                    {
                        this.Visible = false;
                        return;
                    }
                    else
                    {
                        //当工作项不在执行状态时，本控件不显示
                        if (CurrentWorkItem.Status != WorkItemStatus.Executing)
                        {
                            this.Visible = false;
                            return;
                        }

                        //只有WorkItem执行人才可以进行WorkItem操作
                        if (!CurrentWorkItem.ExecutorUserName.Equals(PermissionUtils.StripIrrespectiveCharsForLogOnName(Context.User.Identity.Name), StringComparison.CurrentCultureIgnoreCase))
                        {
                            inputPostilBlock.Visible = false;
                            nextActionSettingBlock.Visible = false;
                            nextActionBlock.Visible = false;
                            return;
                        }

                        if (CurrentActiviy.AllowPostil)
                        {
                            inputPostilBlock.Visible = true;
                            postil.Text = CurrentWorkItem.Postil;
                        }

                        List<ListItem> nextStepItemList = new List<ListItem>();

                        //if ((CurrentWorkItem.WorkItemType == WorkItemType.RejectExecuteSubFlow) || (CurrentWorkItem.WorkItemType == WorkItemType.ApprovalForExitSubFlow))
                        if (CurrentWorkItem.WorkItemType == WorkItemType.ApprovalForExitSubFlow)
                        {
                            WorkItemInfo previousWorkItem = WorkItems.GetWorkItem(CurrentWorkItem.PreviousWorkItemGuid);
                            SubTaskInfo childSubTask = SubTasks.GetSubTask(previousWorkItem.SubTaskGuid);

                            //判断当前的子任务是否完成
                            if (SubTasks.IsSubTaskComplete(childSubTask.ParentSubTaskGuid, childSubTask.TaskGuid, childSubTask.SubFlowGuid, CurrentWorkItem.WorkItemGuid))
                            {
                                ActivityInstanceInfo subFlowActivity = ActivityInstances.GetActivity(childSubTask.ActivityGuid);
                                //启动工作流活动的活动实例
                                ActivityInstanceInfo previousSubFlowActivity = ActivityInstances.GetActivity(subFlowActivity.ActivityGuidOfStartThisSubFlowActivity);

                                PopulateNextActionDropDownList(nextStepItemList, previousSubFlowActivity);

                                AddDistinctListItemToDropDownList(nextStepItemList, new ListItem(subFlowActivity.ActivityName, (int)WorkItemAction.StartSubFlow + "," + subFlowActivity.CodeName + "," + subFlowActivity.SubTaskGuid.ToString() + "," + subFlowActivity.PrototypeGuid.ToString()));
                                AddDistinctListItemToDropDownList(nextStepItemList, new ListItem(Label_DisApproval + "（" + previousWorkItem.ActivityName + "—" + CurrentWorkItem.CreatorDisplayName + "）", (int)WorkItemAction.DisApproval + string.Empty));
                            }
                            else
                            {
                                AddDistinctListItemToDropDownList(nextStepItemList, new ListItem(Label_Approval, (int)WorkItemAction.Approval + string.Empty));
                                AddDistinctListItemToDropDownList(nextStepItemList, new ListItem(Label_DisApproval + "（" + previousWorkItem.ActivityName + "—" + CurrentWorkItem.CreatorDisplayName + "）", (int)WorkItemAction.DisApproval + string.Empty));
                                //AddDistinctListItemToDropDownList(nextStepItemList, new ListItem(Label_DisApproval + "（" + CurrentActiviy.ActivityName + "—" + CurrentWorkItem.CreatorDisplayName + "）", (int)WorkItemAction.DisApproval + string.Empty));
                            }
                        }
                        else
                        {
                            nextStepItemList.Clear();
                            PopulateNextActionDropDownList(nextStepItemList, CurrentActiviy);
                        }

                        nextActionSelect.Items.Clear();
                        for (int i = 0; i < nextStepItemList.Count; i++)
                        {
                            nextActionSelect.Items.Add(nextStepItemList[i]);
                        }

                        DealWithNextActionExecutorArea();
                    }
                }
                #endregion
            }
            else
            {
                //触发下一步选项列表
                //WorkflowChangeNextStepEventArgs workflowNextStepChooseEventArgs = new WorkflowChangeNextStepEventArgs(nextActionSelect.Items);
                //OnChangeNextStep(this, workflowNextStepChooseEventArgs);
            }

            //把 下一步选项列表 放入一个参数内,供 下一个选项处事件 使用
            workflowNextStepChooseEventArgs = new WorkflowChangeNextStepEventArgs(nextActionSelect.Items);
            this.SetWorkflowNextStepChooseEventArgsOriginalItemList(ref workflowNextStepChooseEventArgs);

        }

        private void SetWorkflowNextStepChooseEventArgsOriginalItemList(ref WorkflowChangeNextStepEventArgs args)
        {
            ListItemCollection listCollection = args.ItemList;
            ListItemCollection newListCollection = new ListItemCollection();
            string allListItemInfo = string.Empty;

            //1.第一次请求的时候,将所有的列表项 转换成字符串的形式 放入ViewState中
            if (ViewState["NextStepItems"] == null)
            {
                for (int i = 0; i < listCollection.Count; i++)
                {
                    allListItemInfo += listCollection[i].Text + "$" + listCollection[i].Value + "||";
                }
                ViewState["NextStepItems"] = allListItemInfo;
            }

            if (ViewState["NextStepItems"] != null)
            {
                allListItemInfo = (string)ViewState["NextStepItems"];
            }

            if (string.IsNullOrEmpty(allListItemInfo) == false)
            {
                string[] listItemInfo = allListItemInfo.Split(new string[] { "||" }, StringSplitOptions.RemoveEmptyEntries);
                for (int i = 0; i < listItemInfo.Length; i++)
                {
                    string[] itemInfo = listItemInfo[i].Split('$');
                    if (itemInfo.Length > 1)
                    {
                        ListItem item = new ListItem(itemInfo[0], itemInfo[1]);
                        newListCollection.Add(item);
                    }
                }
            }

            args.OriginalItemList = newListCollection;
        }


        /// <summary>
        /// 在预呈现内部处理 对下一步流向的取舍
        /// </summary>
        /// <param name="e"></param>
        protected override void OnPreRender(EventArgs e)
        {
            OnChangeNextStep(this, workflowNextStepChooseEventArgs);

            if (workflowNextStepChooseEventArgs.IsDealed == true)
            {
                this.nextActionSelect.Items.Clear();
                ListItemCollection itemCollection = workflowNextStepChooseEventArgs.ItemList;
                for (int i = 0; i < itemCollection.Count; i++)
                {
                    this.nextActionSelect.Items.Add(itemCollection[i]);
                }
            }
            base.OnPreRender(e);
        }

        /// <summary>
        /// 下一操作变更事件处理程序
        /// </summary>
        void NextActionSelect_SelectedIndexChanged(object sender, EventArgs e)
        {
            DealWithNextActionExecutorArea();
        }

        /// <summary>
        /// 保存事件处理程序
        /// </summary>
        void SaveButton_Click(object sender, EventArgs e)
        {
            WorkItemInfo currentWorkItem = WorkItems.GetWorkItem(this.WorkItemGuid);

            //执行工作项保存后的事件
            OnSave(this, new WorkflowEventArgs(currentWorkItem));
        }

        /// <summary>
        /// 流转 事件处理程序
        /// </summary>
        void NextStepButton_Click(object sender, EventArgs e)
        {
            if (CurrentWorkItem.Status != WorkItemStatus.Executing)
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.GetType().FullName, "alert('该工作项不在执行状态，可能已有其他人执行');", true);
                return;
            }

            //是否需要设置下个活动的执行人
            ActivityPrototypeInfo nextActivityPrototype = null;

            #region 验证录入信息的完整性

            string selectedValue = nextActionSelect.SelectedValue;
            string[] arrayOfSelectedValue = selectedValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            WorkItemAction? selectedWorkItemAction = null;
            if (arrayOfSelectedValue != null && arrayOfSelectedValue.Length > 0)
            {
                selectedWorkItemAction = (WorkItemAction)int.Parse(arrayOfSelectedValue[0]);
            }

            if (selectedWorkItemAction.HasValue)
            {
                switch (selectedWorkItemAction)
                {
                    case WorkItemAction.StartSubFlow:
                        nextActivityPrototype = ActivityPrototypes.GetActivityPrototype(new Guid(arrayOfSelectedValue[3]));
                        if (string.IsNullOrEmpty(subFlowOrganizationsHidden.Value))
                        {
                            subFlowOrganizationsCustomValidator.IsValid = false;
                            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.GetType().FullName, "alert(\"请选择启动子流程的部门\");", true);
                        }
                        else
                        {
                            string errorOrganization;
                            SubFlowInfo subFlowStarting = SubFlows.GetSubFlowByActivityPrototypeGuid(nextActivityPrototype.PrototypeGuid);
                            bool checkResult = SubTasks.CheckSubTaskHasExectors(subFlowOrganizationsHidden.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries), subFlowStarting, out errorOrganization);

                            if (!checkResult)
                            {
                                subFlowOrganizationsCustomValidator.IsValid = false;
                                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.GetType().FullName, "alert(\"您选择的部门“" + errorOrganization + "”没有可以执行的人员\");", true);
                            }
                        }
                        break;

                    case WorkItemAction.Goto:
                    case WorkItemAction.Next:
                        nextActivityPrototype = ActivityPrototypes.GetActivityPrototype(new Guid(arrayOfSelectedValue[2]));
                        if (nextActivityPrototype != null)
                        {
                            if (!string.IsNullOrEmpty(nextActivityExecutorHidden.Value))
                            {
                                nextActivityPrototype.RequiredUserNames = nextActivityExecutorHidden.Value;
                                ActivityPrototypes.UpdateActivityPrototype(nextActivityPrototype);
                            }
                            else if (!nextActivityPrototype.IsSubFlow)
                            {
                                if (!nextActivityPrototype.CanAssignToExecutor(CurrentUser, ApplicationCodeName) && string.IsNullOrEmpty(nextActivityPrototype.RequiredUserNames))
                                {
                                    nextActivityExecutorCustomValidator.IsValid = false;
                                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.GetType().FullName, "alert(\"没有找到符合条件的执行人,请选择下一流程的具体执行人\");", true);
                                }
                            }
                        }
                        break;
                }
            }
            #endregion

            //执行工作项流转时的事件
            OnSubmit(this, new WorkflowEventArgs(CurrentWorkItem, CurrentActiviy, nextActivityPrototype));
        }

        #region 对外公开的方法

        /// <summary>
        /// 保存意见
        /// </summary>
        public bool WorkflowSave()
        {
            //更新WorkItemName
            if (CurrentWorkItem.WorkItemType == WorkItemType.StartTask)
            {
                if (!SaveTaskInfo(CurrentWorkItem))
                    return false;
            }

            CurrentWorkItem.Postil = postil.Text;
            WorkItems.SaveWorkItem(CurrentWorkItem);

            return true;
        }

        /// <summary>
        ///  处理工作流流转
        /// </summary>
        public bool WorkflowSubmit(WorkflowEventArgs e)
        {
            WorkItemInfo currentWorkItem = e.CurrentWorkItem;
            ActivityInstanceInfo currentActiviyInstance = e.CurrentActivityInstance;
            ActivityPrototypeInfo currentActivityPrototype = CurrentActivityPrototype;
            ActivityPrototypeInfo nextActivityPrototype = e.NextActivityPrototype;

            if (Page.IsValid)
            {
                currentWorkItem.Postil = postil.Text;
                WorkItems.SaveWorkItem(currentWorkItem);

                bool isFinalJudgment = false;

                SubTaskInfo currentSubTask = SubTasks.GetSubTask(currentWorkItem.SubTaskGuid);

                //更新TaskName
                if (currentWorkItem.WorkItemType == WorkItemType.StartTask)
                {
                    if (!SaveTaskInfo(currentWorkItem))
                        return false;
                }

                string selectedValue = nextActionSelect.SelectedValue;
                string[] arrayOfSelectedValue = selectedValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                WorkItemInfo newWorkItem = null;

                WorkItemAction? selectedWorkItemAction = null;
                if (arrayOfSelectedValue != null && arrayOfSelectedValue.Length > 0)
                {
                    selectedWorkItemAction = (WorkItemAction)int.Parse(arrayOfSelectedValue[0]);
                }

                if (selectedWorkItemAction.HasValue)
                {
                    switch (selectedWorkItemAction)
                    {
                        case WorkItemAction.StartSubFlow:
                            if (nextActivityPrototype == null)
                                nextActivityPrototype = ActivityPrototypes.GetActivityPrototype(new Guid(arrayOfSelectedValue[3]));

                            break;
                        case WorkItemAction.ApprovalForExitSubFlow:
                            //创建提交给 子流程发起人的WorkItem
                            ActivityInstanceInfo subflowActivity = ActivityInstances.GetActivity(currentSubTask.ActivityGuid);

                            //启动工作流活动的活动实例
                            ActivityInstanceInfo previousSubFlowActivity = ActivityInstances.GetActivity(subflowActivity.ActivityGuidOfStartThisSubFlowActivity);

                            newWorkItem = new WorkItemInfo();
                            newWorkItem.WorkItemGuid = Guid.NewGuid();
                            newWorkItem.ActivityGuid = previousSubFlowActivity.ActivityGuid;
                            newWorkItem.ActivityName = previousSubFlowActivity.ActivityName;
                            newWorkItem.TaskGuid = currentWorkItem.TaskGuid;

                            //把工作项提交给子任务的发起人
                            newWorkItem.ExecutorUserName = currentSubTask.SponsorUserName;
                            newWorkItem.ExecutorDisplayName = currentSubTask.SponsorDisplayName;
                            newWorkItem.ExecutorFullPath = currentSubTask.SponsorFullPath;

                            newWorkItem.SubTaskGuid = subflowActivity.SubTaskGuid;
                            newWorkItem.WorkItemName = string.Format("{0}-审批子流程-{1}-{2}", previousSubFlowActivity.ActivityName, currentSubTask.SubTaskName, currentSubTask.SponsorUserName);

                            newWorkItem.CreatorUserName = this.CurrentUser.LogOnName;
                            newWorkItem.CreatorDisplayName = this.CurrentUser.DisplayName;
                            newWorkItem.CreatorFullPath = this.CurrentUser.FullPath;

                            newWorkItem.Status = WorkItemStatus.Executing;
                            newWorkItem.WorkItemType = WorkItemType.ApprovalForExitSubFlow;
                            newWorkItem.PreviousWorkItemGuid = currentWorkItem.WorkItemGuid;

                            break;
                        case WorkItemAction.Approval:
                            if (currentWorkItem.WorkItemType == WorkItemType.ApprovalForExitSubFlow)
                            {
                                currentWorkItem.ExecutionResult = WorkItemExecutionResult.Approval;
                                WorkItems.SaveWorkItem(currentWorkItem);
                            }

                            break;
                        case WorkItemAction.DisApproval:
                            if (currentWorkItem.WorkItemType == WorkItemType.ApprovalForExitSubFlow)
                            {
                                currentWorkItem.ExecutionResult = WorkItemExecutionResult.Disapproval;
                                WorkItems.SaveWorkItem(currentWorkItem);

                                WorkItemInfo previousWorkItemInfo = WorkItems.GetWorkItem(currentWorkItem.PreviousWorkItemGuid);
                                ActivityInstances.BackActivity(previousWorkItemInfo.ActivityGuid, currentWorkItem.WorkItemGuid, this.CurrentUser);

                                //重设previousSubTask状态为Executing
                                SubTaskInfo previousSubTask = SubTasks.GetSubTask(previousWorkItemInfo.SubTaskGuid);
                                previousSubTask.Status = SubTaskStatus.Executing;
                                SubTasks.UpdateSubTask(previousSubTask);
                            }

                            break;
                        case WorkItemAction.FinalJudgment:
                            //设置办结标识
                            isFinalJudgment = true;
                            break;
                        case WorkItemAction.Back:
                            Guid previousActivityGuid = new Guid(arrayOfSelectedValue[2]);
                            ActivityInstances.BackActivity(previousActivityGuid, currentWorkItem.WorkItemGuid, this.CurrentUser);
                            break;

                        case WorkItemAction.Goto:
                        case WorkItemAction.Next:
                            if (nextActivityPrototype == null)
                                nextActivityPrototype = ActivityPrototypes.GetActivityPrototype(new Guid(arrayOfSelectedValue[2]));
                            break;
                    }

                    //如果其在一个子流程内部,并且 这是第一次处理这个子任务,那么就更新这个任务的接受时间
                    //在生成一个子任务的时候,其缺省的接受时间为 2000年前的一个日前,因此我们通过这个时间就能判断
                    //这个子任务是否 已经被接受了.
                    if (currentSubTask != null && currentSubTask.AcceptDate <= new DateTime(2000, 1, 2))
                    {
                        SubTasks.UpdateSubTaskAcceptDate(currentSubTask.SubTaskGuid, DateTime.Now);
                    }
                }

                if (newWorkItem != null)
                {
                    WorkItems.CreateWorkItem(newWorkItem);
                }


                //工作流办结
                if (isFinalJudgment)
                {
                    bool activityIsComplete;
                    WorkItems.CompleteWorkItem(currentWorkItem.WorkItemGuid, out activityIsComplete);

                    //如果在某个SubTask内办结，则只办结该SubTask
                    if (currentWorkItem.SubTaskGuid != Guid.Empty)
                        SubTasks.CompleteSubTask(currentWorkItem.SubTaskGuid);
                    else
                        Tasks.CompleteTask(currentWorkItem.TaskGuid, currentWorkItem.WorkItemGuid);
                }
                else
                {
                    bool activityIsComplete;
                    WorkItems.CompleteWorkItem(this.WorkItemGuid, out activityIsComplete);

                    if (nextActivityPrototype != null)
                    {
                        //只更新主流程的活动
                        //更新TaskInfo中当前运行的ActivityCodeName
                        if (nextActivityPrototype.SubFlowGuid == Guid.Empty)
                        {
                            TaskInfo currentTask = Tasks.GetTask(currentWorkItem.TaskGuid);

                            if (nextActivityPrototype.ActivityLevel < currentActiviyInstance.ActivityLevel || activityIsComplete)
                                currentTask.ExecutingActivityCodeName = nextActivityPrototype.CodeName;

                            Tasks.UpdateTask(currentTask);
                        }



                        if (activityIsComplete)
                        {
                            ActivityInstanceInfo activityInstance = new ActivityInstanceInfo(nextActivityPrototype);

                            if (nextActivityPrototype.IsSubFlow)
                            {
                                activityInstance.SubTaskGuid = new Guid(selectedValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries)[2]);
                                string[] organizationIDs = subFlowOrganizationsHidden.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                                activityInstance.ActivityGuidOfStartThisSubFlowActivity = this.CurrentActiviy.ActivityGuid;
                                ActivityInstances.CreateSubFlowActivity(activityInstance, organizationIDs, this.CurrentUser.LogOnName, currentWorkItem.WorkItemGuid);
                            }
                            else
                            {
                                ActivityInstances.CreateActivity(activityInstance, true, this.CurrentUser.LogOnName, currentWorkItem.WorkItemGuid, currentSubTask);
                            }
                        }
                    }

                    //尝试结束子任务
                    if (currentWorkItem.SubTaskGuid != Guid.Empty)
                        SubTasks.TryCompleteSubTask(currentWorkItem.SubTaskGuid);
                }

                //尝试结束Task
                //处理如下情况： 例如主流程中的子流程活动设置为分发并办结，则主流程停止（假办结状态）等待所有子流程处理完毕后自动完成Task
                Tasks.TryCompleteTask(currentWorkItem.TaskGuid);

            }
            else
            {
                return false;
            }
            return true;
        }


        #endregion


        #region 事件

        /// <summary>
        /// 工作项保存时触发的事件
        /// </summary>
        public event WorkflowEventHandler Save;

        /// <summary>
        /// 触发工作项保存时的事件
        /// </summary>
        protected void OnSave(WorkflowController sender, WorkflowEventArgs e)
        {
            if (Save != null)
                Save(sender, e);
        }

        /// <summary>
        /// 工作项流转时触发的事件
        /// </summary>
        public event WorkflowEventHandler Submit;

        /// <summary>
        /// 触发工作项流转时的事件
        /// </summary>
        protected void OnSubmit(WorkflowController sender, WorkflowEventArgs e)
        {
            if (Submit != null)
                Submit(sender, e);
        }

        /// <summary>
        /// 变更下一步操作时触发的事件
        /// </summary>
        public event WorkflowChangeNextStepEventHandler ChanageNextStep;
        /// <summary>
        /// 触发变更工作流下一步操作事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void OnChangeNextStep(WorkflowController sender, WorkflowChangeNextStepEventArgs e)
        {
            if (ChanageNextStep != null)
            {
                ChanageNextStep(sender, e);
                DealWithNextActionExecutorArea();
            }
        }
        #endregion


        #region 属性

        /// <summary>
        /// 活动编码
        /// </summary>
        public string ActivityCodeName
        {
            get { return ViewState["ActivityCodeName"] as string ?? string.Empty; }
            set { ViewState["ActivityCodeName"] = value; }
        }

        /// <summary>
        /// 工作项Guid
        /// </summary>
        public Guid WorkItemGuid
        {
            get
            {
                object obj = ViewState["WorkItemGuid"];
                if (obj != null)
                    return new Guid(obj.ToString());
                else
                    return Guid.Empty;
            }
            set { ViewState["WorkItemGuid"] = value.ToString(); }
        }

        /// <summary>
        /// TaskGuid
        /// </summary>
        public Guid TaskGuid
        {
            get
            {
                object obj = ViewState["TaskGuid"];
                if (obj != null)
                    return new Guid(obj.ToString());
                else
                    return Guid.Empty;
            }
            set { ViewState["TaskGuid"] = value.ToString(); }
        }

        /// <summary>
        /// 任务名称
        /// </summary>
        public string TaskName
        {
            get { return ViewState["TaskName"] as string ?? string.Empty; }
            set { ViewState["TaskName"] = value; }
        }

        public string TaskType
        {
            get { return ViewState["TaskType"] as string ?? string.Empty; }
            set { ViewState["TaskType"] = value; }
        }

        /// <summary>
        /// 部门选择器URL
        /// </summary>
        public string OrganizationSelectorUrl
        {
            get { return ViewState["OrganizationSelectorUrl"] as string ?? "~/Utility/OrganizationSelector.aspx"; }
            set { ViewState["OrganizationSelectorUrl"] = value; }
        }

        /// <summary>
        /// 用户选择器URL
        /// </summary>
        public string UserSelectorUrl
        {
            get { return ViewState["UserSelectorUrl"] as string ?? "~/Utility/UserSelector.aspx"; }
            set { ViewState["UserSelectorUrl"] = value; }
        }

        ///// <summary>
        ///// 工作流流程跟踪URL
        ///// </summary>
        //public string WorkflowTrackingUrl
        //{
        //    get { return ViewState["WorkflowTrackingUrl"] as string ?? "~/WorkflowTracking.aspx"; }
        //    set { ViewState["WorkflowTrackingUrl"] = value; }
        //}

        private string workflowXmlFile = null;
        /// <summary>
        /// 需加载的工作流xoml文件名称
        /// </summary>
        public string WorkflowXmlFile
        {
            get { return workflowXmlFile; }
            set { workflowXmlFile = value; }
        }


        private IUser currentUser;
        /// <summary>
        /// 当前操作用户
        /// </summary>
        public IUser CurrentUser
        {
            get
            {
                if (currentUser == null)
                {
                    if (Context.Request.IsAuthenticated)
                    {
                        currentUser = ChinaCustomsPermissionWrapper.GetUser(PermissionUtils.StripIrrespectiveCharsForLogOnName(Context.User.Identity.Name));
                    }
                }
                return currentUser;
            }
        }

        private WorkItemInfo currentWorkItemDonotUseDirectly;
        /// <summary>
        /// 当前的工作项
        /// </summary>
        private WorkItemInfo CurrentWorkItem
        {
            get
            {
                if (currentWorkItemDonotUseDirectly == null)
                {
                    currentWorkItemDonotUseDirectly = WorkItems.GetWorkItem(this.WorkItemGuid);
                }
                return currentWorkItemDonotUseDirectly;
            }
            set { currentWorkItemDonotUseDirectly = value; }
        }

        private ActivityInstanceInfo currentActiviyDonotUseDirectly;
        /// <summary>
        /// 当前的活动
        /// </summary>
        private ActivityInstanceInfo CurrentActiviy
        {
            get
            {
                if (currentActiviyDonotUseDirectly == null)
                {
                    currentActiviyDonotUseDirectly = ActivityInstances.GetActivity(CurrentWorkItem.ActivityGuid);
                }
                return currentActiviyDonotUseDirectly;
            }
            set { currentActiviyDonotUseDirectly = value; }
        }

        private ActivityPrototypeInfo currentActivityPrototypeDonotUseDirectly;
        /// <summary>
        /// 当前活动的原型
        /// </summary>
        private ActivityPrototypeInfo CurrentActivityPrototype
        {
            get
            {
                if (currentActivityPrototypeDonotUseDirectly == null)
                {
                    currentActivityPrototypeDonotUseDirectly = ActivityPrototypes.GetActivityPrototype(CurrentActiviy.PrototypeGuid);
                }
                return currentActivityPrototypeDonotUseDirectly;
            }
            set { currentActivityPrototypeDonotUseDirectly = value; }
        }

        /// <summary>
        /// 下一步要执行的 活动列表中的 选中项
        /// </summary>
        public ListItem NextActionSeletedItem
        {
            get
            {
                return this.nextActionSelect.SelectedItem;
            }
        }


        /// <summary>
        /// 保存按钮
        /// </summary>
        public LinkButton SaveButton
        {
            get
            {
                EnsureChildControls();
                return this.saveButton;
            }
        }

        /// <summary>
        /// 提交流转按钮
        /// </summary>
        public LinkButton SubmitButton
        {
            get
            {
                EnsureChildControls();
                return this.nextStepButton;
            }
        }
        #endregion

        #region Help Methods

        /// <summary>
        /// 在创建Task时更新TaskName,TaskType
        /// </summary>
        bool SaveTaskInfo(WorkItemInfo currentWorkItem)
        {
            if (currentWorkItem.WorkItemType == WorkItemType.StartTask)
            {
                TaskInfo currentTask = Tasks.GetTask(currentWorkItem.TaskGuid);

                if (string.IsNullOrEmpty(currentTask.TaskName) && string.IsNullOrEmpty(this.TaskName))
                {
                    ScriptManager.RegisterStartupScript(this.Page, this.GetType(), this.GetType().FullName, "alert('必须设置任务名称！')", true);
                    return false;
                }

                if (!string.IsNullOrEmpty(this.TaskName))
                    currentTask.TaskName = this.TaskName;

                if (string.IsNullOrEmpty(this.TaskType) == false)
                {
                    currentTask.TaskType = this.TaskType;
                }

                currentTask.Status = TaskStatus.Executing;
                Tasks.UpdateTask(currentTask);
            }
            return true;
        }

        /// <summary>
        /// 组装NextActionDropDownList的Items
        /// </summary>
        /// <param name="nextListItems">nextListItems</param>
        /// <param name="currentActiviy">当前Activity</param>
        void PopulateNextActionDropDownList(List<ListItem> nextListItems, ActivityInstanceInfo currentActiviy)
        {
            ActivityPrototypeInfo nextActivityPrototype = ActivityPrototypes.GetNextActivityPrototype(currentActiviy.WorkflowGuid, currentActiviy.SubFlowGuid, currentActiviy.CodeName);
            //处理正常流程
            if (nextActivityPrototype != null)
            {
                if (nextActivityPrototype.IsSubFlow)
                {
                    AddDistinctListItemToDropDownList(nextListItems, new ListItem(nextActivityPrototype.ActivityName, (int)WorkItemAction.StartSubFlow + "," + nextActivityPrototype.CodeName + "," + CurrentWorkItem.SubTaskGuid.ToString() + "," + nextActivityPrototype.PrototypeGuid.ToString()));
                }
                else
                {
                    AddDistinctListItemToDropDownList(nextListItems, new ListItem(nextActivityPrototype.ActivityName, (int)WorkItemAction.Next + "," + nextActivityPrototype.CodeName + "," + nextActivityPrototype.PrototypeGuid.ToString()));
                }
            }

            //处理跳转
            if (!string.IsNullOrEmpty(currentActiviy.ActivityCodeNamesForJump))
            {
                string[] activityCodeNamesForJumpArray = currentActiviy.ActivityCodeNamesForJump.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                List<ActivityPrototypeInfo> activityPrototypes;
                if (currentActiviy.SubFlowGuid == Guid.Empty)
                    activityPrototypes = ActivityPrototypes.GetActivityPrototypesOfMainFlow(currentActiviy.WorkflowGuid);
                else
                    activityPrototypes = ActivityPrototypes.GetActivityPrototypesOfSubFlow(currentActiviy.WorkflowGuid, currentActiviy.SubFlowGuid);

                foreach (ActivityPrototypeInfo activityPrototype in activityPrototypes)
                {
                    //不允许跳转到子流程
                    if (activityCodeNamesForJumpArray.Contains<string>(activityPrototype.CodeName) && !activityPrototype.IsSubFlow)
                        AddDistinctListItemToDropDownList(nextListItems, new ListItem(activityPrototype.ActivityName, (int)WorkItemAction.Goto + "," + activityPrototype.CodeName + "," + activityPrototype.PrototypeGuid.ToString()));
                }
            }

            //处理“退回”
            if (currentActiviy.AllowBack && CurrentWorkItem.PreviousWorkItemGuid != Guid.Empty)
            {
                List<WorkItemInfo> previousWorkItems = WorkItems.GetPreviousWorkItemsToThisActivityPrototype(CurrentWorkItem);
                foreach (WorkItemInfo previousWorkItem in previousWorkItems)
                {
                    bool isListItemExist = false;

                    foreach (ListItem li in nextListItems)
                    {
                        if (li.Value.StartsWith((int)WorkItemAction.Back + "," + previousWorkItem.Activity.CodeName + ","))
                        {
                            isListItemExist = true;
                            break;
                        }
                    }

                    //消除重复的人员
                    if (!isListItemExist)
                        nextListItems.Add(new ListItem(Label_Back + "（" + previousWorkItem.ActivityName + "—" + previousWorkItem.ExecutorDisplayName + "）", (int)WorkItemAction.Back + "," + previousWorkItem.Activity.CodeName + "," + previousWorkItem.Activity.ActivityGuid.ToString()));
                }
            }

            //处理办结
            //if (currentActiviy.AllowFinalJudgment || nextActivityPrototype == null)
            if (currentActiviy.AllowFinalJudgment)
            {
                if (currentActiviy.SubFlowGuid != Guid.Empty)
                {
                    SubFlowInfo subFlow = SubFlows.GetSubFlow(currentActiviy.SubFlowGuid);
                    ActivityPrototypeInfo subFlowActivityPrototype = ActivityPrototypes.GetActivityPrototype(subFlow.ActivityPrototypeGuid);

                    if (subFlowActivityPrototype.RequireFeedbackInSubFlow)
                    {
                        SubTaskInfo currenSubTask = SubTasks.GetSubTask(currentActiviy.SubTaskGuid);
                        AddDistinctListItemToDropDownList(nextListItems, new ListItem(Label_Feedback + "（" + currenSubTask.SponsorDisplayName + "）", (int)WorkItemAction.ApprovalForExitSubFlow + string.Empty));
                    }
                    else
                    {
                        AddDistinctListItemToDropDownList(nextListItems, new ListItem(Label_FinalJudgment, (int)WorkItemAction.FinalJudgment + string.Empty));
                    }
                }
                else
                {
                    AddDistinctListItemToDropDownList(nextListItems, new ListItem(Label_FinalJudgment, (int)WorkItemAction.FinalJudgment + string.Empty));
                }
            }
        }

        /// <summary>
        /// 添加不重复的ListItem
        /// </summary>
        void AddDistinctListItemToDropDownList(List<ListItem> nextListItem, ListItem li)
        {
            foreach (ListItem listItem in nextListItem)
            {
                if (listItem.Value.Equals(li.Value))
                    return;
            }

            nextListItem.Add(li);
        }

        /// <summary>
        /// 从通用授权系统获取UserName列表对应的DisplayName列表
        /// </summary>
        /// <param name="userNames">UserName列表，多个UserName用“,”分割</param>
        string GetDisplayNamesFromGeneralPermission(string userNames)
        {
            string[] userNameArray = userNames.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            return GetDisplayNamesFromGeneralPermission(userNameArray);
        }

        /// <summary>
        /// 从通用授权系统获取UserName列表对应的DisplayName列表
        /// </summary>
        /// <param name="userNameArray">UserName数组</param>
        string GetDisplayNamesFromGeneralPermission(string[] userNameArray)
        {
            string displayNames = string.Empty;
            if (userNameArray != null && userNameArray.Length > 0)
            {
                for (int i = 0; i < userNameArray.Length; i++)
                {
                    string displayName = ChinaCustomsPermissionWrapper.GetUser(userNameArray[i]).DisplayName;
                    if (i < userNameArray.Length - 1)
                        displayNames += displayName + ",";
                    else
                        displayNames += displayName;
                }
            }
            return displayNames;
        }

        /// <summary>
        /// 处理设置下一活动执行人区域控件
        /// </summary>        
        void DealWithNextActionExecutorArea()
        {
            WorkItemInfo currentWorkItem = WorkItems.GetWorkItem(this.WorkItemGuid);
            ActivityInstanceInfo currentActiviy = ActivityInstances.GetActivity(currentWorkItem.ActivityGuid);
            ActivityPrototypeInfo nextActivityPrototype = null;

            string selectedValue = nextActionSelect.SelectedValue;
            string[] arrayOfSelectedValue = selectedValue.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);


            WorkItemAction? selectedWorkItemAction = null;
            if (arrayOfSelectedValue != null && arrayOfSelectedValue.Length > 0)
            {
                selectedWorkItemAction = (WorkItemAction)int.Parse(arrayOfSelectedValue[0]);
            }

            if (selectedWorkItemAction.HasValue)
            {
                switch (selectedWorkItemAction)
                {
                    case WorkItemAction.StartSubFlow:
                        nextActivityExecutorArea.Visible = false;
                        subFlowOrganizationsArea.Visible = true;

                        SubTaskInfo subTask = null;
                        if (arrayOfSelectedValue[2] != "00000000-0000-0000-0000-000000000000")
                            subTask = SubTasks.GetSubTask(new Guid(arrayOfSelectedValue[2]));

                        nextActivityPrototype = ActivityPrototypes.GetActivityPrototype(new Guid(arrayOfSelectedValue[3]));

                        if (subTask != null)
                        {
                            subFlowOrganizationsLink.DestinationURL = string.Format(this.OrganizationSelectorUrl + "?ParentOrganizationID={0}&IsOnlyDisplayRelativeTopLevel={1}", subTask.OrganizationID.ToString(), nextActivityPrototype.OnlyShowRelativeTopLevelInOrganizationSelectorOfSubFlow);
                        }
                        else
                        {
                            subFlowOrganizationsLink.DestinationURL = string.Format(this.OrganizationSelectorUrl + "?IsOnlyDisplayRelativeTopLevel={0}", nextActivityPrototype.OnlyShowRelativeTopLevelInOrganizationSelectorOfSubFlow);
                        }

                        break;
                    case WorkItemAction.ApprovalForExitSubFlow:
                        nextActivityExecutorArea.Visible = false;
                        subFlowOrganizationsArea.Visible = false;

                        break;
                    case WorkItemAction.Approval:
                        nextActivityExecutorArea.Visible = false;
                        subFlowOrganizationsArea.Visible = false;

                        break;
                    case WorkItemAction.DisApproval:
                        nextActivityExecutorArea.Visible = false;
                        subFlowOrganizationsArea.Visible = false;

                        break;

                    case WorkItemAction.FinalJudgment:
                        nextActivityExecutorArea.Visible = false;
                        subFlowOrganizationsArea.Visible = false;
                        break;
                    case WorkItemAction.Back:
                        nextActivityExecutorArea.Visible = false;
                        subFlowOrganizationsArea.Visible = false;
                        break;
                    case WorkItemAction.Goto:
                    case WorkItemAction.Next:
                        nextActivityExecutorArea.Visible = true;
                        subFlowOrganizationsArea.Visible = false;

                        nextActivityPrototype = ActivityPrototypes.GetActivityPrototype(new Guid(arrayOfSelectedValue[2]));
                        if (nextActivityPrototype != null)
                        {
                            //只有下个活动允许指定执行者 并且不是第一个活动时 
                            if (nextActivityPrototype.AllowRedesignateExecutor && (!nextActivityPrototype.IsFirstActivityPrototype))
                            {
                                string organizationIDs = nextActivityPrototype.RequiredDepartmentIDs;

                                if (nextActivityPrototype.RequiredRelativeDepartment != RelativeDepartmentLevel.NotSet)
                                {
                                    IUser currentUser = ChinaCustomsPermissionWrapper.GetUser(currentWorkItem.ExecutorUserName);
                                    if (nextActivityPrototype.RequiredRelativeDepartment == RelativeDepartmentLevel.RelativeOneLevel)
                                        organizationIDs = currentUser.Parent.ID;
                                    else if (nextActivityPrototype.RequiredRelativeDepartment == RelativeDepartmentLevel.RelativeTopLevel)
                                        organizationIDs = currentUser.TopOU.ID;
                                }

                                //处于子任务中时将部门设置到该子任务所在部门
                                if (currentWorkItem.SubTaskGuid != Guid.Empty)
                                {
                                    SubTaskInfo currentSubTask = SubTasks.GetSubTask(currentWorkItem.SubTaskGuid);
                                    if (currentSubTask != null)
                                    {
                                        //当下个活动与当前活动位于同一个SubTask时限定organizationIDs
                                        if (currentSubTask.SubFlowGuid == nextActivityPrototype.SubFlowGuid)
                                            organizationIDs = currentSubTask.OrganizationID.ToString();
                                    }
                                }

                                nextActivityExecutorLink.DestinationURL = this.UserSelectorUrl + string.Format("?RoleNames={0}&OrganizationIDs={1}", nextActivityPrototype.RequiredRoles, organizationIDs);
                                nextActivityExecutorLink.Visible = true;
                            }
                            else
                            {
                                nextActivityExecutorLink.Visible = false;
                            }

                            ActivityInstanceInfo nextActivity = ActivityInstances.GetLastActivityByCodeName(nextActivityPrototype.WorkflowGuid, currentActiviy.SubTaskGuid, nextActivityPrototype.CodeName);
                            if (nextActivity != null)
                            {
                                List<string> executorsOfActivity = WorkItems.GetExecutorsOfActivity(nextActivity.ActivityGuid);
                                if (executorsOfActivity != null && executorsOfActivity.Count > 0)
                                {
                                    string[] executorUserNames = executorsOfActivity.ToArray();
                                    nextActivityExecutorLabel.Text = GetDisplayNamesFromGeneralPermission(executorUserNames);
                                    nextActivityExecutorHidden.Value = string.Join(",", executorUserNames);
                                }
                                else
                                {
                                    nextActivityExecutorLabel.Text = GetDisplayNamesFromGeneralPermission(nextActivity.RequiredUserNames);
                                    nextActivityExecutorHidden.Value = nextActivity.RequiredUserNames;
                                }
                            }
                            else if (nextActivityPrototype.SubFlowGuid == Guid.Empty) //仅主流程的显示 RequiredUserNames
                            {
                                nextActivityExecutorLabel.Text = GetDisplayNamesFromGeneralPermission(nextActivityPrototype.RequiredUserNames);
                                nextActivityExecutorHidden.Value = nextActivityPrototype.RequiredUserNames;
                            }
                        }
                        break;
                }
            }

        }

        #endregion

        #region 常量

        /// <summary>
        /// 发起子流程
        /// </summary>
        const string Label_StartSubFlow = "发起子流程";

        /// <summary>
        /// 提交给子流程发起人
        /// </summary>
        const string Label_ApprovalForExitSubFlow = "提交给子流程发起人";

        /// <summary>
        /// 批准
        /// </summary>
        const string Label_Approval = "批准";

        /// <summary>
        /// 不批准(退回)
        /// </summary>
        const string Label_DisApproval = "退回";

        /// <summary>
        /// 办结
        /// </summary>
        const string Label_FinalJudgment = "办结";

        /// <summary>
        /// 反馈
        /// </summary>
        const string Label_Feedback = "反馈";

        /// <summary>
        /// 退回
        /// </summary>
        const string Label_Back = "退回";

        #endregion

    }

    /// <summary>
    /// 工作项操作
    /// </summary>
    public enum WorkItemAction
    {
        /// <summary>
        /// 发起子流程
        /// </summary>
        StartSubFlow = 1,

        /// <summary>
        /// 反馈给子流程发起人
        /// </summary>
        ApprovalForExitSubFlow = 2,

        /// <summary>
        /// 批准
        /// </summary>
        Approval = 3,

        /// <summary>
        /// 不批准
        /// </summary>
        DisApproval = 4,

        /// <summary>
        /// 办结
        /// </summary>
        FinalJudgment = 5,

        /// <summary>
        /// 退回到
        /// </summary>
        Back = 6,

        /// <summary>
        /// 跳转到
        /// </summary>
        Goto = 7,

        /// <summary>
        /// 正常流转
        /// </summary>
        Next = 8,
    }

}
